<?php
/**
 * Samble XML-RPC
 * Samble XML-RPC server class file.
 *
 * @author Lim Afriyadi
 * @package Samble
 * @subpackage xmlrpc
 * @version pre-alpha
 * @license GNU/GPL.
 */
class Xmlrpc_Server
{
    /**
     * XML-RPC connection handler.
     * @var object
     */
    private $oHandler;
    /**
     * Array of registered XML-RPC functions.
     * @var array
     */
    private $aFunctions;
    /**
     * The class singleton instance.
     * @var object
     */
    private static $oInstance;

    private function __CONSTRUCT()
    {
        $this->oHandler = xmlrpc_server_create();
        $this->aFunctions = array();
    }
    /**
     * Grab class single instance.
     * @return object
     */
    public static function getInstance()
    {
        if(!self::$oInstance)
        {
            self::$oInstance = new Xmlrpc_Server();
        }
        return self::$oInstance;
    }
    /**
     * Register a function to be available on XML-RPC via 'method caller'.
     * @param string $sFnName The registered function name.
     * @param object $oInstance Object that own the function.
     * @param string $sAlias XML-RPC method name.
     * @param array $aParameters Array of function parameters.
     */
    public function registerMethod($sFnName,$oInstance,$sAlias,$aParameters)
    {
        if($sAlias == null) $sAlias = $sFnName;
        xmlrpc_server_register_method($this->oHandler, $sFnName, array(&$oInstance,$sAlias));
        $this->aFunctions[$sFnName] =
               array('function'        => $sAlias,
                     'parameters'      => $aParameters);
    }
    /**
     * XML-RPC Method Caller of this class.
     * @param string $sFnName Function name to be called.
     * @param array $aFnParams Function parameters.
     * @return object
     */
    public function callMethod($sFnName,$aFnParams)
    {
        $sFunction = $this->aFunctions[$sFnName]['function'];
        $aParameters = $this->aFunctions[$sFnName]['parameters'];
        $aParams = array();
        foreach($aParameters as $sParameter)
        {
            $aParams[] = $aFnParams[0][$sParameter];
        }
        return call_user_func_array($sFunction, $params);
    }
    /**
     * Process the XML-RPC request and return the result.
     * @return object Return XML object.
     */
    public function processRequest()
    {
        $response = xmlrpc_server_call_method($this->oHandler, file_get_contents('php://input'), null);
        return $response;
    }
}
?>
